package cn.piesat.scanning.vo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class RestUtil {

  private static final Logger logger = LoggerFactory.getLogger(RestUtil.class);
  
  /* 
   * 通过http URL获取rest接口数据
   */
  private final int timeoutInMilliSeconds =  1000 * 60 * 1 ; //1 MINUTE

  /*
   * REST请求服务，获取数据
   */
  public String getRestData(String params) {
    StringBuilder retStr = new StringBuilder();
    URL url = null;
    BufferedReader reader = null;
    URLConnection con;
    try {
      url = new URL(params);
      con = url.openConnection();
      con.setConnectTimeout( this.timeoutInMilliSeconds ); 
      reader = new BufferedReader(  new InputStreamReader(con.getInputStream(),"utf-8"));
      String line = reader.readLine();
      while (line != null) {
        retStr.append(line).append("\r\n");
        line = reader.readLine();
      }
      reader.close();
    } catch (Exception ex1) {
      logger.error("※ 从CIMISS获取数据超时，10分钟后将重试...");
    }finally{
      if(null != reader){
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return retStr.toString();
  }

  /*
   * REST请求服务，存储数据
   */
  public String setRestData(String params,String inString) {
    StringBuilder retStr = new StringBuilder();
    URL url = null;
    BufferedReader reader = null;
    URLConnection con;
    params=params+"&instring="+inString;
    try {
      url = new URL(params);
      con = url.openConnection();
      con.setConnectTimeout( this.timeoutInMilliSeconds ); 
      reader = new BufferedReader(  new InputStreamReader(con.getInputStream()));
      String line = reader.readLine();
      while (line != null) {
        retStr.append(line).append("\r\n");
        line = reader.readLine();
      }
      reader.close();
    } catch (Exception ex1) {
      ex1.printStackTrace();
    }finally{
      if(null != reader){
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return retStr.toString();
  }
  
}
